import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { FileChooser } from '@ionic-native/file-chooser/ngx';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { File } from '@ionic-native/file/ngx';
import { SELECTPEOPLE } from '../../service/constant';
import { RequestService } from '../../service/request/request.service';
import { LoadingController } from '@ionic/angular';
import Config from '../../config/index';
import { TOKEN } from '../../service/constant';
import { UtilsService } from '../../service/utils.service';

@Component({
  selector: 'app-add-document',
  templateUrl: './add-document.component.html',
  styleUrls: ['./add-document.component.scss'],
})
export class AddDocumentComponent implements OnInit {
  filetransfer: FileTransferObject;
  select_people: any[] = [];
  from: any = {
    title: '',
    content: '',
    url: '',
  };
  constructor(
    private router: Router,
    private fileChooser: FileChooser,
    // tslint:disable-next-line: deprecation
    private transfer: FileTransfer,
    private file: File,
    private http: RequestService,
    private loading: LoadingController,
    private utils: UtilsService,
  ) {
    this.filetransfer = this.transfer.create();
  }

  ngOnInit() {
    console.log(123);
    /**
     * 路由监听
     */
    this.router.events.subscribe((res) => {
      if (res instanceof NavigationEnd) {
        if (res.url === '/add-document') {
          this.getInfo();
        }
      }
    });
  }
  // 提交数据
  async Submit() {
    let names = '';
    // 人员过滤选择
    this.select_people.forEach((item: any) => {
      names += ',' + item.username;
    });
    names = names.substring(1);
    if (this.from.title && this.from.content && names) {
      const loading = await this.loading.create({
        message: '数据请求中...',
      });
      await loading.present();
      const data = {
        // 内容
        content: this.from.content,
        // 人员
        names,
        // 标题
        title: this.from.title,
        // url地址
        url: this.from.url,
      };
      this.http.post('gwgl/gwDocument/add', data).subscribe((res) => {
        console.log(res, 'res');
        if (res && res.code === 200) {
          loading.dismiss();
          this.http.showToast('发送成功');
          this.router.navigateByUrl('/tabs/tab1');
        } else {
          loading.dismiss();
        }
      });
    } else {
      this.http.showToast('请填写内容!');
    }
  }
  // 标题变化
  ChangeTitle(val: any) {
    this.from.title = val.detail.value;
  }
  // 内容变化
  ChangeContent(val: any) {
    this.from.content = val.detail.value;
  }
  getInfo() {
    this.select_people = localStorage.getItem(SELECTPEOPLE) ? JSON.parse(localStorage.getItem(SELECTPEOPLE)) : [];
  }
  // 选择单位
  SelecUnit() {
    this.router.navigateByUrl('/select-peop');
  }
  // 选择人员
  SelectPersonnel() {
    this.router.navigateByUrl('/select-peop');
  }
  // 文件上传
  async Upload(fileurl: string) {
    const loading = await this.loading.create({
      message: '文件上传中...',
    });
    await loading.present();
    const fileExtend = fileurl.substring(fileurl.lastIndexOf('.') + 1);
    const resultFilePath = `${Date.now()}.${fileExtend}`;
    const options: FileUploadOptions = {
      fileKey: 'file',
      fileName: resultFilePath,
      headers: {
        'X-Access-Token': localStorage.getItem(TOKEN),
      },
      params: {
        biz: 'temp',
      },
    };

    this.filetransfer
      .upload(fileurl, Config.baseUrl + 'sys/common/upload', options)
      .then((res: any) => {
        const data = JSON.parse(res.response);
        if (data.code === 0) {
          this.from.url = data.message;
        }
        loading.dismiss();
        this.utils.showToast('文件上传成功', 'top');
      })
      .catch((err) => {
        loading.dismiss();
        this.utils.showToast('文件上传失败', 'top');
      });
  }
  // 附件上传
  AttUpload() {
    this.fileChooser.open().then((res) => {
      this.Upload(res);
    });
  }
}
